<?php
namespace app\forms;

use yii\base\Model;
use app\models\Bookmark;
class BookmarkForm extends Model
{
    public $id;
    public $title;
    public $url;
    public $cateId;
    public $userId;
    
    const SCENARIO_CREATE = 'create';
    const SCENARIO_MODIFY = 'modify';
    const SCENARIO_REMOVE = 'remove';
    const SCENARIO_CHANGE_CATE = 'changeCate';
    
    public function rules() {
        return [
            ['userId', 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_MODIFY, self::SCENARIO_REMOVE, self::SCENARIO_CHANGE_CATE]],
            ['userId', 'number', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_MODIFY, self::SCENARIO_REMOVE]],
            [['title', 'url', 'cateId'], 'required', 'on' => [self::SCENARIO_CREATE, self::SCENARIO_MODIFY]],
            ['cateId', 'number', 'on' => ['self::SCENARIO_CREATE, self::SCENARIO_MODIFY']],
            [['id'], 'required', 'on' => [self::SCENARIO_MODIFY, self::SCENARIO_REMOVE, self::SCENARIO_CHANGE_CATE]],
            [['id'], 'number', 'on' => [self::SCENARIO_MODIFY, self::SCENARIO_REMOVE]],
        	['cateId', 'number', 'on' => [self::SCENARIO_CHANGE_CATE]],
        	['cateId', 'exist', 'targetClass' => 'app\models\Cate', 'targetAttribute' => 'id', 'on' => [self::SCENARIO_CHANGE_CATE]],
        ];
    }
    
    /**
     * 创建一个书签
     * @return \app\models\Bookmark
     */
    public function create() {
    	if (!$this->validate()) {
    		throw new FormParamNotValidateException();
    	}
    	
        $bookmark = new Bookmark();
        $bookmark->cateId = intval($this->cateId);
        $bookmark->userId = $this->userId;
        $bookmark->title = $this->title;
        $bookmark->url = $this->url;
        $bookmark->createTime = date('Y-m-d H:i:s');
        $bookmark->save();
        
        return $bookmark;
    }
    
    /**
     * 修改
     */
    public function modify() {
    	if (!$this->validate()) {
    		throw new FormParamNotValidateException();
    	}
        $bookmark = new Bookmark();
        $bookmark->setOldAttribute('id', intval($this->id));
        $bookmark->cateId = intval($this->cateId);
        $bookmark->title = $this->title;
        $bookmark->url = $this->url;
        return $bookmark->update();
    }
    
    public function changeCate() {
    	if (!$this->validate()) {
    		throw new FormParamNotValidateException();
    	}
    	return Bookmark::updateAll(['cateId' => $this->cateId], ['id' => $this->id, 'userId' => $this->userId]);
    }
    
    /**
     * 删除
     */
    public function remove() {
    	if (!$this->validate()) {
    		throw new FormParamNotValidateException();
    	}
        return Bookmark::deleteAll(['id' => intval($this->id), 'userId' => $this->userId]);
    }
}

?>